﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Cashier_Interface;
using Cashier_Service;
using Cashier.utils;
using Cashier_Utils;
using Cashier.prints;
using System.Text.RegularExpressions;

namespace Cashier.goods
{
    public partial class GoodsListControl : UserControl, IDataGridViewData, IReloadData, IPrinter
    {
        private MainForm mainform;
        private GoodsService goodsService;
        private static GoodsListControl goodsListControl;
        private CategoryService categoryService;
        private long categoryid = 0; //商品类别
        private ComboBox cellComboBox = new ComboBox(); //单元格编辑事件
        private PrintParameter printParameter = new PrintParameter(); //打印参数对象
        private int printCopies = 0; //打印条码数量
        private Object oldEditValue; //单元格编辑之前的数据

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mainform"></param>
        private GoodsListControl(MainForm mainform)
        {
            InitializeComponent();
            this.mainform = mainform;
            this.dataGridView1.ImplementsInstance = this;
            this.goodsService = new GoodsService();
            this.categoryService = new CategoryService();

            this.treeViewCategory1.IReloadData = this;
            this.treeViewCategory1.InitialTreeViewCategory();
            cellComboBox.SelectedIndexChanged += new EventHandler(cellComboBox_SelectedIndexChanged);

            this.ControlsSetRights();
            this.Dock = DockStyle.Fill;

            //打印条码设置
            printParameter.BarcodeCopies = 4;
            printParameter.BarcodeMarkHeight = 80;
            printParameter.BarcodeMarksInRow = 4;
        }

        /// <summary>
        /// 返回控件实例
        /// </summary>
        /// <param name="mainform"></param>
        /// <returns></returns>
        public static GoodsListControl GetGooldsListControl(MainForm mainform)
        {
            if (goodsListControl == null)
                goodsListControl = new GoodsListControl(mainform);
            goodsListControl.RefreshDataGridViewData();
            return goodsListControl;
        }

        #region 功能方法实现

        /// <summary>
        /// 打开保存商品窗口
        /// </summary>
        /// <param name="goodsid"></param>
        private void OpenGoodsAddForm(long goodsid)
        {
            GoodsAddForm addForm = new GoodsAddForm(this.mainform, this, goodsid);
            addForm.ShowDialog();
        }

        /// <summary>
        /// 控件设置权限
        /// </summary>
        private void ControlsSetRights()
        {
            DataTable rightsTable = mainform.Admin.RolePurviewtable;
            Button[] buttons = { button_add, button_query };
            RightsforControls.RightsforButton(rightsTable, buttons);
            ContextMenuStrip[] menuStrips = { contextMenuStrip_dgv };
            RightsforControls.RightsforContextMenuStrip(rightsTable, menuStrips); 
        }

        /// <summary>
        /// 打印预览
        /// </summary>
        private void PrintPreview()
        {
            PrintPreviewDialog printPreviewDialog = new PrintPreviewDialog();
            printPreviewDialog.Document = printDocument1;
            printPreviewDialog.PrintPreviewControl.Zoom = 1;
            printPreviewDialog.ShowDialog();
        }

        #endregion

        #region IDataGridViewData 成员

        void IDataGridViewData.EnterkeyEventHandler()
        {
            try
            {
                if (dataGridView1.Rows.Count > 0 && dataGridView1.SelectedRows.Count > 0)
                {
                    long goodsid = (long)dataGridView1.SelectedRows[0].Cells[0].Value;
                    this.OpenGoodsAddForm(goodsid);
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }
        
        void IDataGridViewData.GenerateGridViewColumns(DataGridView dgv)
        {
            try
            {
                dgv.AutoGenerateColumns = false;
                dgv.Columns.Clear();
                dgv.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("id", null, true, 0, null, null, false, false));
                dgv.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("barcode", "商品条码", true, 14, ActKey.LEFT, ActKey.LEFT, true, false));
                dgv.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("name", "名称", true, 20, ActKey.LEFT, ActKey.LEFT, true, false));
                dgv.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("categoryname", "分类", true, 8, ActKey.LEFT, ActKey.LEFT, true, false));
                dgv.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("norm", "规格", true, 8, ActKey.LEFT, ActKey.LEFT, true, false));
                dgv.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("price_cost", "进货价", false, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
                dgv.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("price_sale", "销售价", false, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
                dgv.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("discount", "折扣率", false, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
                dgv.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("is_vipprice", "VIP折扣", false, 8, ActKey.CENTER, ActKey.CENTER, true, false));
                dgv.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("stock", "库存", true, 8, ActKey.RIGHT, ActKey.RIGHT, true, false));
                dgv.Columns.Add(GenearteDataGridViewColumn.GetDataGridViewDataFieldColumn("lasttime", "入库日期", true, 10, ActKey.CENTER, ActKey.CENTER, true, false));

                DataTable rightsTable = mainform.Admin.RolePurviewtable;
                if (rightsTable != null)
                {
                    DataRow[] rows = rightsTable.Select("code='goods_edit'");
                    if (rows.Length != 1)
                    {
                        this.dataGridView1.Columns["price_cost"].ReadOnly = true;
                        this.dataGridView1.Columns["discount"].ReadOnly = true;
                        this.dataGridView1.Columns["price_sale"].ReadOnly = true;
                        this.dataGridView1.Columns["is_vipprice"].ReadOnly = true;
                    }
                    else if (rows.Length == 1)
                    {
                        List<DataItem> list = new List<DataItem>();
                        list.Add(DataItem.GetDataItem("是", "true"));
                        list.Add(DataItem.GetDataItem("否", "false"));
                        cellComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                        cellComboBox.DataSource = list;
                        cellComboBox.DisplayMember = "displayMember";
                        cellComboBox.ValueMember = "valueMember";
                        this.dataGridView1.Controls.Add(cellComboBox);
                        cellComboBox.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        void IDataGridViewData.GetBindingData(int rowindex, int pageindex, int pagesize)
        {
            try
            {
                String barcode = textBox_barcode.Text.Trim();
                String name = textBox_name.Text.Trim();
                decimal discount = checkBox_discount.Checked ? 0.01M : 0M;
                bool? isvipprice = null;
                if (checkBox_isvip.Checked)
                    isvipprice = true;
                int stock = 0;
                DataTable dt = goodsService.GetGoodsTable(pageindex, pagesize, barcode, name, categoryid, discount, isvipprice, stock,
                    null, "id");
                this.dataGridView1.DataSource = dt;
                if (dt != null && dt.Rows.Count > 0)
                {
                    if (rowindex > 0)
                        dataGridView1.Rows[0].Selected = false;
                    dataGridView1.Rows[rowindex].Selected = true;
                }
                dataGridView1.Columns[0].Visible = false;

                mainform.SetPageInfo(dataGridView1.Recordcount, pageindex, pagesize);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        long IDataGridViewData.GetBindingDataRecord()
        {
            long record = 0;
            try
            {
                String barcode = textBox_barcode.Text.Trim();
                String name = textBox_name.Text.Trim();
                decimal discount = checkBox_discount.Checked ? 0.01M : 0M;
                bool? isvipprice = null;
                if (checkBox_isvip.Checked)
                    isvipprice = true;
                int stock = 0;
                String suppliername = String.Empty;
                record = goodsService.GetGoodsRecord(barcode, name, categoryid, discount, isvipprice, stock);
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return record;
        }

        #endregion

        #region 控件事件

        /// <summary>
        /// 新增供货商信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_add_Click(object sender, EventArgs e)
        {
            this.OpenGoodsAddForm(0);
        }

        /// <summary>
        /// 查询供货商信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_query_Click(object sender, EventArgs e)
        {
            this.RefreshDataGridViewData();
        }

        /// <summary>
        /// 文本框键盘事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            int keyValue = (int)e.KeyChar;
            if (keyValue == 13)
            {
                this.RefreshDataGridViewData();
            }
        }

        /// <summary>
        /// DataGridView 单元格双击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                long goodsid = (long)this.dataGridView1.Rows[e.RowIndex].Cells[0].Value;
                this.OpenGoodsAddForm(goodsid);
            }
        }

        /// <summary>
        /// DataGridView格式化数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("lasttime"))
            {
                DateTime date = (DateTime)e.Value;
                e.Value = date.ToShortDateString();
            }
            else if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("stock"))
            {
                if (Int32.Parse(e.Value.ToString()) < Config.STOCK_WARING)
                {
                    e.CellStyle.ForeColor = Color.Red;
                }
            }
        }

        /// <summary>
        /// 单元格单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0 && e.ColumnIndex > 0)
                {
                    oldEditValue = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                    this.dataGridView1.CurrentCell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    bool b = this.dataGridView1.BeginEdit(true);
                    if (this.dataGridView1.Columns[e.ColumnIndex].Name.Equals("is_vipprice"))
                    {
                        Rectangle rect = this.dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false);
                        String cellValue = this.dataGridView1.CurrentCell.FormattedValue.ToString();
                        cellComboBox.Text = cellValue;
                        cellComboBox.Left = rect.Left;
                        cellComboBox.Top = rect.Top;
                        cellComboBox.Width = rect.Width;
                        cellComboBox.Height = rect.Height;
                        cellComboBox.Visible = true;
                    }
                    else
                        cellComboBox.Visible = false;
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 单元格值改变事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                long id = (long)this.dataGridView1.Rows[e.RowIndex].Cells[0].Value;
                String columnName = this.dataGridView1.CurrentCell.OwningColumn.Name;
                object cellValue = this.dataGridView1.CurrentCell.Value;
                if (cellValue != null && !String.IsNullOrEmpty(cellValue.ToString()) &&
                    Regex.IsMatch(cellValue.ToString(), RegexExpress.DECIMAL_TWO_BITS))
                {
                    if (columnName.Equals("price_cost"))
                        this.goodsService.UpdateGoodsPriceCost(id, (decimal)cellValue);
                    else if (columnName.Equals("price_sale"))
                        this.goodsService.UpdateGoodsPriceSale(id, (decimal)cellValue);
                    else if (columnName.Equals("discount"))
                        this.goodsService.UpdateGoodsDiscount(id, (decimal)cellValue);
                    else if (columnName.Equals("is_vipprice"))
                        this.goodsService.UpdateIsvipprice(id, (bool)cellValue);
                }
                else
                {
                    this.dataGridView1.Rows[e.RowIndex].Cells[columnName].Value = oldEditValue;
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 单元格数据格式验证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.RowIndex >= 0 && (e.ColumnIndex == 5 || e.ColumnIndex == 6 || e.ColumnIndex == 7))
            {
                if (e.FormattedValue != null && !String.IsNullOrEmpty(e.FormattedValue.ToString()) &&
                    Regex.IsMatch(e.FormattedValue.ToString(), RegexExpress.DECIMAL_TWO_BITS))
                {
                    e.Cancel = false;
                }
                else
                {
                    e.Cancel = true;//数据格式不正确则还原
                    dataGridView1.CancelEdit();
                }
            }
        }

        /// <summary>
        /// CellComboBox选择项变动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cellComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.dataGridView1.CurrentCell != null)
                {
                    ComboBox comboBox = sender as ComboBox;
                    if (comboBox != null)
                    {
                        if (comboBox.Text.Equals("是"))
                            this.dataGridView1.CurrentCell.Value = true;
                        else
                            this.dataGridView1.CurrentCell.Value = false;
                        comboBox.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 打印所有商品条形码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolButton_printBarcode_all_Click(object sender, EventArgs e)
        {
            printParameter.Dgv = this.dataGridView1;
            printParameter.IsPrintSelectedRows = false;
            this.PrintPreview();
        }

        /// <summary>
        /// 打印选择商品条形码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolButton_printBarcode_selected_Click(object sender, EventArgs e)
        {
            printParameter.Dgv = this.dataGridView1;
            printParameter.IsPrintSelectedRows = true;
            this.PrintPreview();
        }

        /// <summary>
        /// 打印设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolButton_printSetting_Click(object sender, EventArgs e)
        {
            PrintBarcodeSetForm barcodeSetForm = new PrintBarcodeSetForm(mainform, printDocument1.PrinterSettings, printParameter);
            barcodeSetForm.ShowDialog();
        }

        #endregion

        #region 刷新数据

        /// <summary>
        /// 刷新数据
        /// </summary>
        public void RefreshDataGridViewData()
        {
            this.dataGridView1.LoadingData();
        }

        #endregion


        #region 重载事件

        /// <summary>
        /// 重写键盘事件
        /// </summary>
        /// <param name="keyData"></param>
        /// <returns></returns>
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool b = base.ProcessCmdKey(ref msg, keyData);
            switch (keyData)
            {
                case Keys.F8:
                    this.RefreshDataGridViewData();
                    break;
                case Keys.F9:
                    this.OpenGoodsAddForm(0);
                    break;
                case Keys.Up:
                    if (!this.dataGridView1.Focused)
                        this.dataGridView1.Focus();
                    break;
                case Keys.Down:
                    if (!this.dataGridView1.Focused)
                        this.dataGridView1.Focus();
                    break;
            }
            return b;
        }

        #endregion


        #region IReloadData 成员

        void IReloadData.ReloadDataGridViewData(object param)
        {
            long cid = (long)param;
            if (cid >= 0)
                this.categoryid = cid;
            this.RefreshDataGridViewData();
            if (categoryid < 0)
            {
                this.treeViewCategory1.SetTreeNodeCategoryCount();
            }
        }

        #endregion

        #region DataGridView右键菜单

        /// <summary>
        /// 新增商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_add_Click(object sender, EventArgs e)
        {
            this.OpenGoodsAddForm(0);
        }

        /// <summary>
        /// 编辑商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_edit_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.Rows.Count > 0 && dataGridView1.SelectedRows.Count > 0)
                {
                    long goodsid = (long)dataGridView1.SelectedRows[0].Cells[0].Value;
                    this.OpenGoodsAddForm(goodsid);
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_delete_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.Rows.Count > 0 && dataGridView1.SelectedRows.Count > 0)
                {
                    DialogResult result = MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < dataGridView1.SelectedRows.Count; i++)
                        {
                            long goodsid = (long)dataGridView1.SelectedRows[i].Cells[0].Value;
                            sb.Append(goodsid).Append(",");
                        }
                        if (sb.Length > 0)
                        {
                            sb.Remove(sb.Length - 1, 1);
                            int count = goodsService.DeleteGoods(sb.ToString());
                            if (count > 0)
                            {
                                MessageBox.Show("删除成功！");
                                this.RefreshDataGridViewData();
                                this.treeViewCategory1.SetTreeNodeCategoryCount();
                            }
                            else
                                MessageBox.Show("删除失败！");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        /// <summary>
        /// 复制商品条码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem_copy_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.SelectedRows.Count > 0)
            {
                Clipboard.SetText(this.dataGridView1.SelectedRows[0].Cells["barcode"].Value.ToString());
            }
        }

        #endregion     

        #region IPrinter 成员

        /// <summary>
        /// 打印所有页数据
        /// </summary>
        /// <returns></returns>
        DataGridView IPrinter.GetAllRows()
        {
            try
            {
                ((IDataGridViewData)this).GetBindingData(0, 0, 0);               
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
            return this.dataGridView1;
        }

        /// <summary>
        /// 打印选定数据
        /// </summary>
        /// <returns></returns>
        DataGridView IPrinter.GetSelectedRows()
        {
            return this.dataGridView1;
        }

        /// <summary>
        /// 显示隐藏列
        /// </summary>
        /// <param name="columnname"></param>
        void IPrinter.VisibleColumn(string columnname)
        {
            try
            {
                if (this.dataGridView1.Columns[columnname].Visible)
                    this.dataGridView1.Columns[columnname].Visible = false;
                else
                    this.dataGridView1.Columns[columnname].Visible = true;
            }
            catch (Exception ex)
            {
                LogsUtil.Record(ex);
            }
        }

        #endregion

        #region 打印事件

        /// <summary>
        /// 打印每一页前发生
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument1_QueryPageSettings(object sender, System.Drawing.Printing.QueryPageSettingsEventArgs e)
        {
            
        }

        /// <summary>
        /// 打印中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            printCopies = PrintBarcode.PrintGoodsBarcode128(printParameter, e, printCopies);
            int rowCount = printParameter.Dgv.Rows.Count;
            if (printParameter.IsPrintSelectedRows)
                rowCount = printParameter.Dgv.SelectedRows.Count;

            if (printParameter.StartRowIndex > 0)
            {
                if (printParameter.StartRowIndex > (rowCount - 1))
                {
                    printParameter.PageIndex = 1;
                    printParameter.StartRowIndex = 0;
                }
                else
                    printParameter.PageIndex += 1;
            }
        }

        #endregion

    }
}
